import websockets
import asyncio
import threading
import json

ws = None


class Set_Proxies_V2:
    def __init__(self) -> None:
        self.Start()

    async def handle_connection(self, websocket, path):
        global ws
        ws = websocket
        while True:
            try:
                message = await websocket.recv()
                print("Received message:", message)
            except:
                print("报错")
                break

    def start_server(self):
        asyncio.set_event_loop(asyncio.new_event_loop())
        loop = asyncio.get_event_loop()

        async def run_server():
            server = await websockets.serve(self.handle_connection, "localhost", 11111)
            await server.wait_closed()

        loop.run_until_complete(run_server())

    def Start(self):
        thread = threading.Thread(target=self.start_server)
        thread.start()

    def Set_Ip(self, host, port):
        if ws is not None:
            send_data = {"task": "set", "host": str(host), "port": port}
            asyncio.run_coroutine_threadsafe(ws.send(json.dumps(send_data)), ws.loop)

    def Clear_Ip(self):
        if ws is not None:
            send_data = {"task": "clear"}
            asyncio.run_coroutine_threadsafe(ws.send(json.dumps(send_data)), ws.loop)
